#!/usr/bin/python
#coding=utf-8

import time
import threading
import datetime
import json
from socket import *

import sys
import os
import logging

from waveshare_TSL2591 import TSL2591

import Adafruit_DHT

global timer    #30S的定时器
global sendFlag #发送标志位
    
def socket_send_data(temperature,humidity,in_time,lux, infrared, visible):
    # serverName = '192.168.0.110'
    serverName = '120.79.69.157'
    serverPort = 12000
    clientSocket = socket(AF_INET,SOCK_STREAM)
    clientSocket.connect((serverName,serverPort))
    
    msg = {'temperature':temperature , 'humidity':humidity , 'in_time':in_time ,'lux':lux , 'infrared':infrared , 'visible':visible}
    json_msg = json.dumps(msg)
    clientSocket.sendall(json_msg)
    clientSocket.close()

#获取传感器信息
def get_and_send_data():
    in_time = get_now_time()
    temperature, humidity = get_dht_data()
    lux, infrared, visible = get_tsl_data()

    socket_send_data(temperature, humidity, in_time, lux, infrared, visible)

    global sendFlag
    sendFlag = False

#获取当前时间
def get_now_time():
    current_time = datetime.datetime.now()
    format_time  = datetime.datetime.strftime(current_time,'%Y-%m-%d %H:%M:%S')
    return format_time

#获取DHT22的数据
def get_dht_data():
    sensor_dht22 = Adafruit_DHT.DHT22
    pin = 23  #GPIO23
    humidity, temperature = Adafruit_DHT.read_retry(sensor_dht22, pin , 15 , 1)
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
    else:
        print('Failed to get reading. Try again!')
    return temperature,humidity


#获取TSL25911的数据
def get_tsl_data():
    sensor_tsl25911 = TSL2591.TSL2591()
    # sensor.SET_InterruptThreshold(0xff00, 0x0010)
    lux = sensor_tsl25911.Lux
    print('Lux: %d'%lux)
    infrared = sensor_tsl25911.Read_Infrared
    print('Infrared light: %d'%infrared)
    visible = sensor_tsl25911.Read_Visible
    print('Visible light: %d'%visible)
    return lux, infrared, visible


#定时器
def set_timer():
    global sendFlag
    sendFlag = True
    timer = threading.Timer(5,set_timer)
    timer.start()

if __name__ == '__main__':
    global sendFlag
    sendFlag = False
    timer = threading.Timer(5,set_timer)
    timer.start()
    while(True):
        if(sendFlag):
            get_and_send_data()
